//
//  UsetimeModel.swift
//  EarbudsDatabase
//
//  Created by 李然 on 2024/6/15.
//

import Foundation
import RealmSwift
import MoyoungLib

public class UsetimeModel: Object, Storable {
    
    @Persisted(primaryKey: true) public var id: UUID
    
    @Persisted public var address: String = ""
    @Persisted public var date: Date = Date()
    @Persisted public var updateTime: Date = Date()
    @Persisted public var detail: List<UsetimeDetailModel>
    @Persisted public var usageFrequency = 0
    
    @Persisted public var totalCallTimeMin: Int = 0
    @Persisted public var totalAudioTimeMin: Int = 0
    @Persisted public var totalStandbyTimeMin: Int = 0
    @Persisted public var totalShutDownTimeMin: Int = 0
    
    public func update(_ list: [UsetimeDetailModel],
                       usageFrequency: Int,
                       address: String) {
        EasepodsDB.update {
            self.usageFrequency = usageFrequency
            self.address = address
            self.detail.removeAll()
            self.detail.append(objectsIn: list)
            
            self.totalCallTimeMin = detail.filter{ $0.useType == .call }.reduce(0, { $0 + $1.useTimeMin })
            self.totalAudioTimeMin = detail.filter{ $0.useType == .audio }.reduce(0, { $0 + $1.useTimeMin })
            self.totalStandbyTimeMin = detail.filter{ $0.useType == .standby }.reduce(0, { $0 + $1.useTimeMin })
            self.totalShutDownTimeMin = detail.filter{ $0.useType == .shutdown }.reduce(0, { $0 + $1.useTimeMin })
        }
    }
    
    /// 是空的
    public var isEmpty: Bool {
        return (totalCallTimeMin + totalAudioTimeMin + totalStandbyTimeMin + totalShutDownTimeMin) == 0
    }
    
    /// 总使用时间
    public var totalTimeMin: Int {
        return self.totalCallTimeMin + self.totalAudioTimeMin + self.totalStandbyTimeMin
    }
    
    /// 实际使用时间
    public var actualTimeMin: Int {
        return self.totalCallTimeMin + self.totalAudioTimeMin
    }
}

public enum UsetimeUseType : Int {
    
    case shutdown = 0

    case standby = 1

    case audio = 2

    case call = 3
}


public class UsetimeDetailModel: EmbeddedObject {
    
    @Persisted public var typeRawValue: Int = 0

    @Persisted public var startTimeMin: Int = 0

    @Persisted public var useTimeMin: Int = 0
    
    public var useType: UsetimeUseType {
        return UsetimeUseType(rawValue: typeRawValue) ?? .shutdown
    }
}
